package org.osomit.sacct.provider.impl.spring;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.DisposableBean;
import org.osomit.sacct.provider.iface.AccountProvider;

/**
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 *         Date: Jul 6, 2009
 *
 */
public class AccountFactoryBean implements FactoryBean, InitializingBean, DisposableBean {

    private String accountName;

    private String accountPassword;

    private AccountProvider provider;

    public AccountFactoryBean(AccountProvider provider, String accountName) {
        this.accountName = accountName;
        this.accountPassword = null;
        this.provider = provider;
    }

    //wiring in default password in case the provider does not work or is inactive
    public AccountFactoryBean(AccountProvider provider, String accountName, String accountPassword) {
        this.accountName = accountName;
        this.accountPassword = accountPassword;
        this.provider = provider;
    }

    public Object getObject() throws Exception {

        return this.accountPassword;
    }


    public Class getObjectType() {

        return String.class;
    }


    public boolean isSingleton() {
        return false;
    }


    public void afterPropertiesSet() throws Exception {
        if(this.provider != null && this.provider.isActive()){
            this.accountPassword = this.provider.getAccountPassword(this.accountName);
        }
    }

    public void destroy() throws Exception {
        if(this.accountPassword != null){
            this.accountPassword = this.accountPassword.replaceAll(".", " ");
        }
    }
}
